package com.appsl.digitalparking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.appsl.manager.Redirection;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Favourites extends Activity 
{
	private ListView lvFavourites;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{	
		//Considerar ordenar alfabeticamente, por # de views o por cercania (Pier) 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_favourites);
	
		populateListView();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.favourites, menu);
		return true;
	}
	
	private void populateListView()
	{
		lvFavourites = (ListView)findViewById(R.id.lstFavoritos);	
		
		SQLiteDatabase db = openOrCreateDatabase("DigitalParking.db", MODE_PRIVATE, null);
		Cursor crs = db.rawQuery("SELECT idlugar, nombre, direccion FROM Lugar", null);
		crs.moveToFirst();
		
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		
		for (int i=0; i<crs.getCount(); i++)
		{
			Map<String, String> datum = new HashMap<String, String>(2);
			
			datum.put("item", crs.getString(1));
			datum.put("subitem", crs.getString(2));
			data.add(datum);
			crs.moveToNext();
		}
		
		SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,
												  new String[] { "item", "subitem" },
												  new int[] { android.R.id.text1, android.R.id.text2 });									
		lvFavourites.setAdapter(adapter);
		crs.close();
		db.close();
		
		lvFavourites.setOnItemClickListener
		(
			new OnItemClickListener() 
			{
				public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
				{
					//Getting data from selected item
					String itm = ((TextView)(view.findViewById(android.R.id.text1))).getText().toString();
										
					//Preparing message for next activity
					Intent intent = new Intent(Favourites.this, com.appsl.digitalparking.Map.class);
					intent.putExtra("locName", itm);
					//Redirection.goToMap(Favourites.this, intent);
					Redirection.goToDetalleLugar(Favourites.this, itm);
				}
			}
		);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) 
	    { //Back key pressed
	    	Redirection.goToMap(this);
	    	//Redirection.goToFavMap(this);
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
